package dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;

public abstract class GenericRepository <T> {

	protected Class<T> type;

	public GenericRepository(Class<T> type) {
		this.type = type;
	}

	public void insert(T t) {
		Session s = HibernateUtil.getSessionFactory().openSession();

		Transaction tx = s.beginTransaction();
		s.save(t);

		tx.commit();		
	}

	public void delete(T t) {
		Session s = HibernateUtil.getSessionFactory().openSession();

		Transaction tx = s.beginTransaction();
		s.delete(t);

		tx.commit();		
	}

	public void update(T t) {
		Session s = HibernateUtil.getSessionFactory().openSession();

		Transaction tx = s.beginTransaction();
		s.update(t);
	
		tx.commit();		
	}

	public T getById(Long id) {

		Session session = HibernateUtil.getSessionFactory().openSession();

		T t = (T)session.get(type, id);
		session.close();

		return t;
	}

	public List<T> getAllObjects() {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Criteria criteria =
				session.createCriteria(type);

		return criteria.list();
	}
}
